<?PHP

class OP_Layout{
	var $layouts, $sidebars, $key, $load_type, $classname;
	
	var $layouts_define = array(
		0=>array('main'),
		1=>array('main','sidebar'),
		2=>array('sidebar','main'),
		3=>array('sidebar','main','sidebar'),
		4=>array('sidebar','sidebar','main'),
		5=>array('main','sidebar','sidebar')
	);
	
	function OP_Layout(){
		if(!get_option('op_layout')){
			$this->layouts = array('default'=>array('main','sidebar1'),'footer'=>array('column1','column2','column3'));
			// Make sure active template is onepress and it is not the first time it has been activated.
			if(get_option('template') == 'onepress' && !strpos($_SERVER['REQUEST_URI'],'themes.php?activated=true')){
				add_option('op_layout',$this->layouts);
			}
		}
		else{
			$this->layouts = get_option('op_layout');
		}
		
		if (is_admin()) { // For admin sidebar registration
			add_action('admin_menu', array(&$this,'_registerAllSidebars'));
		}
		
		// op_navigation needs to occur in admin & public.
		// admin needs to be able to evaluate if is hooked
		add_action('op_navigation', 'op_navigation');
		
		global $pagenow;
		if(!is_admin() || $pagenow == 'profile.php'){ // Register appropriate sidebars for user based on template
			add_action('template_redirect', array(&$this,'_registerAllSidebars'));
			add_action('template_redirect', array(&$this,'add_styles'));
			add_action('template_redirect', array(&$this,'add_scripts'));
			
			add_action('wp_head', 'op_favicon');
			add_action('wp_head', 'op_meta_title');
			add_action('wp_head', 'op_meta_description');
			add_action('wp_head', 'op_feeds');
			add_action('wp_head', 'fix_ie');
			
			add_action('op_header', 'op_header');
			add_action('op_header_content', 'op_header_content');
			add_action('op_welcome', 'op_welcome');

			add_action('wp_footer', 'op_footer');
			add_action('op_footer_content', 'op_footer_content');
			add_action('op_footer_signature', 'op_footer_signature');
			if (defined('WP_DEBUG') && WP_DEBUG)
				add_action('op_footer_debug', 'op_footer_debug');
		}
	}
	
	function _registerAllSidebars(){
		$this->_getKey();	// get template key
		$this->_registerSidebar('default',$this->layouts['default']);
		$this->_registerSidebar('footer',$this->layouts['footer']);
		
		if(is_admin()){
			$layouts_to_load = array_diff_key($this->layouts,array('default'=>'','footer'=>''));
			foreach($layouts_to_load as $layout_title => $layout){
				$this->_registerSidebar($layout_title,$layout);
			}			
		}
		else{
			$layout = $this->layouts[$this->key];
			$this->_registerSidebar($this->key,$layout);
		}

	}
	
	function _registerSidebar($layout_title, $layout){
		$old_title = $layout_title;
		$layout_title = explode('_',$layout_title);
		if($layout_title[0] != $old_title){
			$type = $layout_title[0];
			$layout_title = $layout_title[1];
		}
		else{
			$layout_title = $old_title;
			$type = '';
		}

		foreach($layout as $column){

			$type_id = $type == '' ? '' : $type.'_'; // if not a standard layout, add type to front of it
			$type_title = $type == '' ? '' : ucfirst($type).' ';
			
			$defaults = array(
				'before_widget' => '<div id="%1$s" class="widget %2$s">'.
				                   '<div class="hd"><div class="hc"></div></div>'.
			  	                   '<div class="bd"><div class="bc">'.
					               '<div class="s">',
				'after_widget' =>  '</div>'.
								   '</div></div>'.
								   '<div class="ft"><div class="fc"></div></div>'.
								   '</div>'
				);

			$name = $type_title.' '.ucfirst($layout_title).' '.ucfirst($column);
			$id = $type_id.$layout_title.'-'.$column;

			register_sidebar(array_merge($defaults,array('name'=>$name,'id'=>$id)));
		}
	}
	
	function add_styles() {
		$url = get_bloginfo('template_directory').'/';
	}
	
	/**
	 * This mimics the WP tepmlate_load functionality.  Figure out what template we are going to load with render()
	 */
	function _getKey(){
		$classnames = array();
		if ( is_search()) {
			$key = $classnames[] = 'search';
			$classnames[] = 'multiple';
		} else if ( is_home()) {
			$key = $classnames[] = 'home';
			$classnames[] = 'multiple';
		} else if ( is_single()) {
			$key = $classnames[] = 'single';
		} else if ( is_page()) {
			global $wp_query;
			$page_slug = $wp_query->post->post_name;
			if($this->layouts['page_'.$page_slug]){
				$key = $classnames[] = 'page_'.$page_slug; // if the page has a custom layout, use that
			}
			else{ // if page doesn't have a custom layout
				$parent_id = $wp_query->post->post_parent; // get the page's parent page
				if($parent_id != NULL){ // if parent page exists
					while($post = get_post($parent_id)){
						$page_slug = $post->post_name; // get the slug for the parent page
						if($this->layouts['page_'.$page_slug]){ // if the parent page has a custom layout, use that
							$key = $classnames[] = 'page_'.$page_slug;
							break;
						}
						
						$parent_id = $post->post_parent;
						if($parent_id == 0){
							$key = $classnames[] = 'page';
							break;
						}
					}
				}
				else{
					$key = $classnames[] = 'page';
				}
			}
			$classnames[] = 'single';
			
		} else if ( is_category()) {
			$cat_id = absint( get_query_var('cat'));
			$category =& get_category($cat_id);
			
			$classnames[] = 'category';
			$classnames[] = 'multiple';
			
			if($category->slug != NULL && $this->layouts['category_'.$category->slug]){
				$key = 'category_'.$category->slug;
				$classnames[] = 'categoryid_'.$cat_id;
				$classnames[] = 'category_'.$category->slug;
			}
			else{ // if not customized look to see if a parent category is.
				$parent_id = $category->parent;
				if($parent_id != 0){
					while($category =& get_category($parent_id)){
						if($this->layouts['category_'.$category->slug]){
							$key = $classnames[] = 'category_'.$category->slug;
							$classnames[] = 'categoryid_'.$category->term_id;
							break;
						}
						
						$parent_id = $category->parent;
						
						if($parent_id == 0){
							$key = 'category';
							break;
						}
					}
				}
				else{
					$key = 'category';	
				}
			}
		} else if ( is_tag()) {
			$classnames[] = 'tag';
			$classnames[] = 'multiple';
			
			$tag = get_query_var('tag');
			if($tag != NULL) { 
				$classnames[] = 'tag_'.$tag;	
				if ($this->layouts['tag_'.$tag]){
					$key = 'tag_'.$tag;
				}
			}
			$key = 'tag';
		} else if ( is_author()) {
			$key = $classnames[] = 'author';
			$classnames[] = 'multiple';
		} else if ( is_archive()) {
			$key = $classnames[] = 'archive';
			$classnames[] = 'multiple';
		} else if ( is_search()){
			$key = $classnames[] = 'search';
			$classnames[] = 'multiple';
		} else{
			$key = $classnames[] = 'default';
			$classnames[] = 'multiple';
		}
		
		$this->load_type = isset($this->load_type) ? $this->load_type : $key;  // set load type to be used by our hook
		$this->key = array_key_exists($key, $this->layouts) ? $key : 'default';
		
		if($this->key == 'default' && !in_array('default',$classnames)) $classnames[] = 'default';
		$this->classname = implode(' ',$classnames);
	}
	
	function add_scripts() {}
	
	function get_layout_class($layout){
		// There are a number of permutations of columns, determine which and
		// generate a CSS class that can be used to style each combination uniquely
		$layout_options = array(
			'main'=>1,
			'sidebar1 main'=>2,
			'main sidebar1'=>3,
			'sidebar2 main'=>4,
			'main sidebar2'=>5,
			'sidebar1 main sidebar2'=>6,
			'sidebar2 main sidebar1'=>7,
			'sidebar1 sidebar2 main'=>8,
			'sidebar2 sidebar1 main'=>9,
			'main sidebar1 sidebar2'=>10,
			'main sidebar2 sidebar1'=>11,
			);
		
		$lookup = implode(' ', $layout);
		if (array_key_exists($lookup, $layout_options) != TRUE)
			$lookup = 'main';
		return 'layout'.$layout_options[$lookup];
	}

	function get_footer_layout_class($layout){
		$num = is_array($layout) ? count($layout) : 1;
		return 'layout'.$num;
	}

	
	function render($args=array()){
		$layout = isset($this->layouts[$this->key]) ? $this->layouts[$this->key] : $this->layouts['default'];
		$class = $this->get_layout_class($layout);
		$sort_layout = $layout;

		// Sort layout columns by priority.  They need to be executed in the correct order so widget content can register itself
		usort($sort_layout, create_function('$a,$b', '$correct = array("main","sidebar1","sidebar2"); return array_keys($correct, $a) > array_keys($correct, $b) ? 1 : -1;'));

		if(get_query_var('preview') == 1 && $this->render_preview()){ // is preview
			return;
		}
				
		// Define ids to be used in markup
		$ids = array('main'=>'main','sidebar1'=>'sidebar','sidebar2'=>'sidebar2');

		foreach($sort_layout as $column){
			ob_start();
			
			echo '<div id="',$ids[$column],'_wrap" class="',$class,'"><div id="',$ids[$column],'">',
					'<div class="hd"><div class="hc"></div></div>',
            		'<div class="bd"><div class="bc">',
            		'<div class="s">';
			
            // If it is a special type, such as login
            if($column=='main' && in_array($this->load_type,array('login','register','lostpassword','profile'))){
				do_action('op_pre_main',$this->load_type,$args);
				do_action('op_post_main',$this->load_type,$args);
			}
			else{ // otherwise, render main
				dynamic_sidebar($this->key.'-'.$column);
			}
			
			echo '</div>',
				 '</div></div>',
				 '<div class="ft"><div class="fc"></div></div>',
				 '</div></div>';
				
			// assign $main, $sidebar1, and $sidebar2
			$$column = ob_get_clean();
		}
		// Now loop through and emit each column and its content
		echo '<div id="content">',
		     '<div class="hd"><div class="hc"></div></div>',
			 '<div class="bd"><div class="bc">',
     		 '<div id="content_s" class="s">';


		foreach($layout as $column){
			// echo $main, $sidebar1, and $sidebar2
			echo $$column;
		}
		echo '<span class="forclear"></span>';
		
		echo '</div>',
			 '</div></div>',
			 '<div class="ft"><div class="fc"></div></div>',
			 '</div>';
	}
	
	function render_preview(){
		global $wp_registered_widgets,$wp_registered_sidebars;
		
		$sidebar_widgets = wp_get_sidebars_widgets();

		if(count($sidebar_widgets['default-main']) == 0){
			// Now loop through and emit each column and its content
			echo '<div id="content">',
			     '<div class="hd"><div class="hc"></div></div>',
				 '<div class="bd"><div class="bc">',
	     		 '<div id="content_s" class="s">';
	
			include(TEMPLATEPATH.'/widgets/template.content_body.php');
			 // Default values for content body widget
			$options = array(
				'content_layout'	=> array('title','date','post-body','tags','div','categories','edit-link','comments'),
				'advanced'			=> array(
					'author_pre'		=> 	'by ',
					'time_pre'			=> 	'at ',
					'time_format'		=> 	'',
					'date_format'		=> 	'F j, Y',
					'more_link'			=>	 'Read the rest of this entry &raquo;',
					'tag_label'			=> 	'Tags: ',
					'tag_before'		=> 	'',
					'tag_separator'		=>	', ',
					'tag_after'			=>	'',
					'category_label'	=>	'Categories: ',
					'category_separator'	=>	', ',
					'category_parents'		=> 	'',
					'comment_link_none'		=> 	'No Comments &#187;',
					'comment_link_one'		=>	'1 Comment &#187;',
					'comment_link_multiple'	=>	'% Comments &#187;'
			));
			
			echo '<div id="main_wrap" class="layout3"><div id="main">',
					'<div class="hd"><div class="hc"></div></div>',
            		'<div class="bd"><div class="bc">',
            		'<div class="s">';
            
            echo '<div class="widget_op_content_body"><div class="hd"><div class="hc"></div></div><div class="bd"><div class="bc"><div class="s">';
			render_op_contentbody($options['content_layout'], $options['advanced']);
			echo '</div></div></div><div class="ft"><div class="fc"></div></div></div>';
			
			echo '</div>',
				 '</div></div>',
				 '<div class="ft"><div class="fc"></div></div>',
				 '</div></div>';
			
			// Render Sidebar with default Wordpress content -- reflects that found in sidebar template in Kubrick
			echo '<div id="sidebar_wrap" class="layout3"><div id="sidebar">',
					'<div class="hd"><div class="hc"></div></div>',
            		'<div class="bd"><div class="bc">',
            		'<div class="s">';
            
            // Pages widget		
			echo '<div class="widget"><div class="hd"><div class="hc"></div></div><div class="bd"><div class="bc"><div class="s">';
			wp_list_pages('title_li=<h2>Pages</h2>' );
			echo '</div></div></div><div class="ft"><div class="fc"></div></div></div>';
			
			// Archives widget
			echo '<div class="widget"><div class="hd"><div class="hc"></div></div><div class="bd"><div class="bc"><div class="s">';
			echo '<li><h2>Archives</h2><ul>';
			wp_get_archives('type=monthly');
			echo '</ul></li>';
			echo '</div></div></div><div class="ft"><div class="fc"></div></div></div>';
			
			// Categories widget
			echo '<div class="widget"><div class="hd"><div class="hc"></div></div><div class="bd"><div class="bc"><div class="s">';
			wp_list_categories('show_count=1&title_li=<h2>Categories</h2>');
			echo '</div></div></div><div class="ft"><div class="fc"></div></div></div>';
			
			// Bookmarks widget
			echo '<div class="widget"><div class="hd"><div class="hc"></div></div><div class="bd"><div class="bc"><div class="s">';
			wp_list_bookmarks();
			echo '</div></div></div><div class="ft"><div class="fc"></div></div></div>';
			
			// Meta widget
			echo '<div class="widget"><div class="hd"><div class="hc"></div></div><div class="bd"><div class="bc"><div class="s">';
			echo '<li><h2>Meta</h2><ul>';
			wp_register();
			echo '<li>';
			wp_loginout();
			echo '</li>',
				'<li><a href="http://validator.w3.org/check/referer" title="This page validates as XHTML 1.0 Transitional">Valid <abbr title="eXtensible HyperText Markup Language">XHTML</abbr></a></li>',
				'<li><a href="http://gmpg.org/xfn/"><abbr title="XHTML Friends Network">XFN</abbr></a></li>',
				'<li><a href="http://wordpress.org/" title="Powered by WordPress, state-of-the-art semantic personal publishing platform.">WordPress</a></li>';
			wp_meta();
			echo '</ul>',
				'</li>';
			echo '</div></div></div><div class="ft"><div class="fc"></div></div></div>';	
			
			echo '</div>',
				 '</div></div>',
				 '<div class="ft"><div class="fc"></div></div>',
				 '</div></div>';
			
			echo '<span class="forclear"></span>';
			
			echo '</div>',
				 '</div></div>',
				 '<div class="ft"><div class="fc"></div></div>',
				 '</div>';
		}
		else{
			return false;
		}
	}
	
	function render_footer(){
		$isempty = TRUE;
		$footer = isset($this->layouts['footer']) ? $this->layouts['footer'] : '';

		ob_start();
		if(is_array($footer)){
			echo '<div id="column_wrap" class="layout'.count($footer).'">';
			for($i=0; $i<count($footer); $i++){
				echo '<div class="column order'.($i+1).' '.$footer[$i].'">';
				ob_start();
				
				dynamic_sidebar('footer'.'-'.$footer[$i]);
				$sidebar = ob_get_clean();
				if (empty($sidebar)){
					echo "&nbsp;";
					$isempty = FALSE;
				}
				else
				{
					echo $sidebar;
					$isempty = FALSE;
				}
				echo '</div>';
			}
			echo '<span class="forclear"></span></div>';
		}

		// if the footer is empty don't emit anything
		if ($isempty == FALSE)
			return ob_get_clean();
		
		ob_end_clean();	
		return '';
	}
}


?>